package xhwl.insurance.morepic.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import xhwl.insurance.R;
import xhwl.insurance.event.FreshPicEvent;
import xhwl.insurance.http.bean.ImageItem;
import xhwl.insurance.morepic.adapter.util.CustomConstants;
import xhwl.insurance.morepic.adapter.util.ImageDisplayer;


public class ImagePublishAdapter extends BaseAdapter
{
	private List<ImageItem> mDataList = new ArrayList<ImageItem>();
	private Context mContext;

	public ImagePublishAdapter(Context context, List<ImageItem> dataList)
	{
		this.mContext = context;
		this.mDataList = dataList;
	}

	public int getCount()
	{
		// 多返回一个用于展示添加图标
		if (mDataList == null)
		{
			return 1;
		}
		else if (mDataList.size() == CustomConstants.FORUM_MAX_IMAGE_SIZE)
		{
			return CustomConstants.FORUM_MAX_IMAGE_SIZE;
		}


		else
		{
			return mDataList.size() + 1;
		}
	}

	public Object getItem(int position)
	{
		if (mDataList != null
				&& mDataList.size() == CustomConstants.MAX_IMAGE_SIZE)
		{
			return mDataList.get(position);
		}else if (mDataList != null&& mDataList.size() == CustomConstants.FORUM_MAX_IMAGE_SIZE){
			return mDataList.get(position);
		}

		else if (mDataList == null || position - 1 < 0
				|| position > mDataList.size())
		{
			return null;
		}
		else
		{
			return mDataList.get(position - 1);
		}
	}

	public long getItemId(int position)
	{
		return position;
	}

	@SuppressLint("ViewHolder")
	public View getView(final int position, View convertView, ViewGroup parent)
	{
		//所有Item展示不满一页，就不进行ViewHolder重用了，避免了一个拍照以后添加图片按钮被覆盖的奇怪问题
		convertView = View.inflate(mContext, R.layout.item_publish, null);
		ImageView imageIv = (ImageView) convertView.findViewById(R.id.item_grid_image);
		ImageView imageDelet = (ImageView) convertView.findViewById(R.id.iv_delet_icon);

		if (isShowAddItem(position))
		{
			imageIv.setImageResource(R.drawable.btn_add_pic);
//			imageIv.setBackgroundResource(R.color.bg_gray);
			imageDelet.setVisibility(View.GONE);
		}
		else
		{
			final ImageItem item = mDataList.get(position);
			ImageDisplayer.getInstance(mContext).displayBmp(imageIv, item.thumbnailPath, item.sourcePath);
			imageDelet.setVisibility(View.VISIBLE);
		}
imageDelet.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
		removeImg(position);
	}
});
		return convertView;
	}
	private void removeImg(int location)
	{
		if (location + 1 <= mDataList.size())
		{
			mDataList.remove(location);
		}
		EventBus.getDefault().post(new FreshPicEvent());
	}
	private boolean isShowAddItem(int position)
	{
		int size = mDataList == null ? 0 : mDataList.size();
		return position == size;
	}

}
